﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SwiftMVVM
{
    internal static class Extensions
    {
        /// <summary>
        /// Somewhat thread safe method to add items to a dictionary
        /// </summary>
        /// <typeparam name="TKey">The key type</typeparam>
        /// <typeparam name="TValue">The value type</typeparam>
        /// <param name="dictionary">The dictionary to get the item from</param>
        /// <param name="lockObject">Object used to lock access to the dictionary</param>
        /// <param name="key">The key for the item</param>
        /// <param name="createFunc">The function to create the new item if it does not exist in the dictionary already</param>
        /// <returns>The value currently in the dictionary or added to it by createFunc</returns>
        public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary,
            object lockObject, TKey key, Func<TKey, TValue> createFunc)
        {
            if (createFunc == null) { throw new ArgumentNullException("createRoutine"); }
            if (dictionary == null) { throw new ArgumentNullException("dictionary"); }
            if (lockObject == null) { throw new ArgumentNullException("lockObject"); }
            TValue result;
            if (!dictionary.TryGetValue(key, out result))
            {
                lock (lockObject)
                {
                    if (!dictionary.TryGetValue(key, out result))
                    {
                        dictionary.Add(key, result = createFunc(key));
                    }
                }
            }
            return result;
        }
    }
}
